package com.spring.design.prototype;

import java.io.*;

/**
 * 原型模式
 * 案例：spring中创建Bean时用到，属性相关对象不同
 */
public class Sheep implements Cloneable, Serializable {

    private String name;

    private Integer age;

    private String color;

    public Sheep friend;

    public Sheep() {
    }

    public Sheep getFriend() {
        return friend;
    }

    public void setFriend(Sheep friend) {
        this.friend = friend;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Sheep(String name, Integer age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    //默认的克隆方法,只复制基本类型和string
    @Override
    protected Object clone() {
        Object deep = null;
        try {
            //完成基本的克隆
            deep = super.clone();
            //对引用类型单独处理,深拷贝1-----如果有多个引用则写起来太麻烦
            Sheep sheep1 = (Sheep)deep;
            sheep1.friend = (Sheep) friend.clone();
            return sheep1;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    //深拷贝2，序列化,推荐使用
    public Object deepClone(){
        //创建流对像
        ByteArrayOutputStream bos =null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis =null;
        ObjectInputStream ois =null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //当前对象以对象流的方式输出
            oos.writeObject(this);
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Sheep copyObj = (Sheep)ois.readObject();

            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
